package com.pixels;

import com.Math.Vector2D;
import com.game.Components.Asteroid;
import com.game.Components.Bullet;
import com.game.Components.Ship;
import com.pixels.graphics.Drawer;
import com.pixels.input.Controller;
import com.pixels.input.InputHandler;

public class Game {

	public Controller controls;
	Asteroid[] astr;
	Ship ship;
	int width, height;
	Asteroid astro;
	
	int level =1;

	public Game(int width, int height) {
		this.width = width;
		this.height = height;

		controls = new Controller();
		ship = new Ship();
		makeAstroids(level);
	}

	public void tick(InputHandler input) {

		controls.tick(input);
		ship.tick(controls);

		for (int i = 0; i < astr.length; i++) {
			if (astr[i] != null) {
				astr[i].move();
				Vector2D v = new Vector2D(astr[i].pos);
				v.subtract(ship.pos);

				if (v.length() < ship.radius + astr[i].radius && ship.visible == true) {
					ship.destroy();
				}
				for (Bullet b : ship.bullets) {
					if (astr[i] != null) {
						Vector2D bulletColl = new Vector2D(astr[i].polygon.center);
						bulletColl.subtract(b.pos);
						if (bulletColl.length() < astr[i].radius) {
							if (astr[i].level > 1) {
								astr[i].downGrade();
								ship.score += 20;
								addSmallAst(i);
							} else {
								astr[i] = null;
								ship.score += 10;
							}
							b.destroy();

						}
					}
				}
			}
		}

		if (allNull()) {
			level++;
			makeAstroids(level);
		}
	}

	void makeAstroids(int num) {
		astr = new Asteroid[num*2];
		for (int i = 0; i < num; i++) {
			astr[i] = new Asteroid(level);
		}
	}

	boolean allNull() {
		for (int i = 0; i < astr.length; i++) {
			if (astr[i] != null) {
				return false;
			}
		}
		return true;
	}

	public void addSmallAst(int i) {
		for (int j = 0; j < level*2; j++) {
			if (astr[j] == null) {
				astr[j] = new Asteroid(astr[i].level);
				astr[j].pos.x = astr[i].pos.x;
				astr[j].pos.y = astr[i].pos.y;
				break;
			}
		}
	}

	public void draw(Drawer draw) {
		for (Asteroid a : astr) {
			if (a != null)
				a.draw(draw);
		}
		ship.draw(draw);
	}
}
